package com.wlz.heartbeat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * @author wlz
 * @date 2022-07-09  4:32 下午
 */
@Slf4j
public class MyHeartBeatNettyClient {

    public static void main(String[] args) {

        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new StringEncoder());

                            socketChannel.pipeline().addLast(new MyHeartBeatNettyClientHandler());
                        }
                    });

            log.info(" netty client start .... ");
            ChannelFuture cf = bootstrap.connect("127.0.0.1", 9000).sync();

            log.info(" =========  {}  ======= ", cf.channel().localAddress());

            Channel channel = cf.channel();
            String text = "Heartbeat Packet";
            Random random = new Random();
            while (channel.isActive()) {
                int num = random.nextInt(8);
                Thread.sleep(2 * 1000);
                channel.writeAndFlush(text);
            }

        } catch (Exception e) {
            log.error("MyHeartBeatNettyClient error: {}", e);
        } finally {
            group.shutdownGracefully();
        }


    }
}
